#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>
#include "Thread.hpp"

// struct ThreadInfo
// {
//     pthread_t _tid;
//     std::string _threadname;
// };

const int defaultnum = 10;

template<class T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }

    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void Wake()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }

    std::string GetThreadName(pthread_t tid)
    {
        for(const auto& x : _threads)
        {
            if(x.Gettid() == tid)
            {
                return x.Name();
            }
        }
        return "UnknowThread";
    }
public:
    static void* HandlerTask(void* args)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while(true)
        {
            tp->Lock();
            while(tp->IsQueueEmpty())
            {
                tp->ThreadSleep();
            }
            T t = tp->Pop();
            tp->Unlock();
            t();
            std::cout << name << " hander a task " << t.GetResult() << std::endl;
        }
        return nullptr;
    }

    void Start()
    {
        for(int i = 0; i < _threads.size(); ++i)
        {
            _threads[i].Run();
        }
    }

    T Pop()
    {
        T ret = _tasks.front();
        _tasks.pop();
        return ret;
    }

    void Push(T& t)
    {
        Lock();
        _tasks.push(t);
        Wake();
        Unlock();
    }

    static ThreadPool<T>* GetInstance()
    {
        if(nullptr == _tp)
        {
            pthread_mutex_lock(&_lock);
            if(nullptr == _tp)
            {
                std::cout << "log: singleton create done first!" << std::endl;
                _tp = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&_lock);
        }
        return _tp;
    }

private:
    ThreadPool(int num = defaultnum) : _threads(num, Thread(HandlerTask, this))
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_cond,nullptr);
    }
    ~ThreadPool()
    {
        for(auto& thread : _threads) thread.Join();
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
    ThreadPool(const ThreadPool<T> &) = delete;
    const ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;
private:
    std::vector<Thread> _threads;
    std::queue<T> _tasks;
    
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T>* _tp;
    static pthread_mutex_t _lock;
};


template<class T>
ThreadPool<T>* ThreadPool<T>::_tp = nullptr;

template<class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;